package controllers

import (
	"encoding/json"
	"github.com/astaxie/beego/logs"
	services "tinyrdm/backend/services"
	"tinyrdm/backend/types"
)

var pubLog = logs.GetLogger("PubSub")

type PubSubController struct {
	BaseController
}

type PubSubReqData struct {
	Method  string `json:"method"`
	Server  string `json:"server"`
	Channel string `json:"channel"`
	Payload string `json:"payload"`
}

var pubSub = services.Pubsub()

func (c *PubSubController) Handler() {
	pubSub.Start(c.context())
	var req PubSubReqData
	err := json.Unmarshal(c.Ctx.Input.RequestBody, &req)
	if err != nil {
		logs.Error(err, string(c.Ctx.Input.RequestBody))
		c.ErrorJson(err)
		return
	}
	var resp any
	switch req.Method {
	case "Publish":
		resp = pubSub.Publish(req.Server, req.Channel, req.Payload)
		break
	case "StartSubscribe":
		resp = pubSub.StartSubscribe(req.Server)
		break
	case "StopSubscribe":
		resp = pubSub.StopSubscribe(req.Server)
		break

	case "Start":

		break
	case "StopAll":
		pubSub.StopAll()
		break
	default:
		resp = types.JSResp{
			Success: false,
			Msg:     "未找到该方法",
			Data:    nil,
		}
		pubLog.Printf("not found: %s", req.Method)
	}
	if resp == nil {
		resp = types.JSResp{
			Success: true,
			Msg:     "Successful",
			Data:    nil,
		}
	}
	c.postJson(resp)
}
